package com.bw.main

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.base.app.RoutePath
import com.bw.common.base.BaseActivity
import com.bw.main.adapter.MainPageAdapter
import com.bw.main.databinding.ActivityMainBinding
import com.bw.main.tab.NormalTabView
import com.bw.main.tab.RoundTabView
import dagger.hilt.android.AndroidEntryPoint
import me.majiajie.pagerbottomtabstrip.NavigationController
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener

@AndroidEntryPoint
@Route(path = RoutePath.PATH_MAIN_PAGE)
class MainActivity : BaseActivity<ActivityMainBinding>() {

    private lateinit var mNavController: NavigationController
    private var fragments = arrayListOf<Fragment>()
    private lateinit var mPagerAdapter: MainPageAdapter

    //配置需要授权的权限
    private var needUserPermissions= arrayListOf(
        Manifest.permission.CAMERA,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
    )
    private var unGrantPermission = arrayListOf<String>()
    private var hasUnGranted = false
    override fun getLayoutId(): Int = R.layout.activity_main



    override fun initViews() {
        //底部导航
        mNavController = mDataBinding.mainBottomNav.custom()
            .addItem(newNormalTabItem(R.drawable.home_gray, R.drawable.home_red, "首页"))
            .addItem(newNormalTabItem(R.drawable.cate_gray, R.drawable.cate_red, "放映厅"))
            .addItem(newRoundTabItem(R.drawable.add, R.drawable.add, "发布"))
            .addItem(newNormalTabItem(R.drawable.news, R.drawable.news_selected, "直播"))
            .addItem(newNormalTabItem(R.drawable.mine_gray, R.drawable.mine_red, "我的"))
            .build()

        //使用ARouter路由获取页面
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_HOME).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_MOVIE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_LIVE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_MINE).navigation() as Fragment)


        mPagerAdapter = MainPageAdapter(supportFragmentManager, fragments, FragmentPagerAdapter.BEHAVIOR_SET_USER_VISIBLE_HINT)
        mDataBinding.mainViewPager.apply {
            adapter = mPagerAdapter
            offscreenPageLimit = 3
        }

        mNavController.addTabItemSelectedListener(object : OnTabItemSelectedListener {
            override fun onSelected(index: Int, old: Int) {
                when(index){
                    0,1-> {
                        mDataBinding.mainViewPager.currentItem = index
                    }
                    2 -> {
                        ARouter.getInstance().build(RoutePath.PATH_PUBLISH_PAGE).navigation()
                        mNavController.setSelect(old) //恢复之前样式
                    }
                    3,4 -> {
                        mDataBinding.mainViewPager.currentItem = index - 1
                    }
                }
            }

            override fun onRepeat(index: Int) {
                if (index == 2){
                    ARouter.getInstance().build(RoutePath.PATH_PUBLISH_PAGE).navigation()
                }
            }
        })

        mDataBinding.mainViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                when(position){
                    0,1 -> mNavController.setSelect(position)
                    2,3 -> mNavController.setSelect(position + 1)
                }
            }

            override fun onPageScrollStateChanged(state: Int) {

            }

        })
        //临时发起用户权限
        mDataBinding.mainViewPager.postDelayed({
            autoRequestPermission()
        },2000)




    }
    private fun newNormalTabItem(defaultIcon: Int, checkedIcon: Int, title: String): BaseTabItem {
        return NormalTabView(this@MainActivity).apply {
            initData(defaultIcon, checkedIcon, title)
            setDefaultTextColor(com.bw.common.R.color.common_color_text_gray)
            setCheckedTextColor(com.bw.common.R.color.red)
        }
    }

    private fun newRoundTabItem(defaultIcon: Int, checkedIcon: Int, title: String): BaseTabItem{
        return RoundTabView(this@MainActivity).apply {
            initData(defaultIcon, checkedIcon, title)
            setDefaultTextColor(com.bw.common.R.color.common_color_text_gray)
            setCheckedTextColor(com.bw.common.R.color.red)
        }
    }

    private fun autoRequestPermission():Boolean{
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            unGrantPermission.clear()


            //检查有哪些未授权
            needUserPermissions.forEach {
                var state = checkSelfPermission(it)
                if(state == PackageManager.PERMISSION_DENIED) {
                    unGrantPermission.add(it)
                }
            }

            if(unGrantPermission.size>0){
                //发起权限申请
                requestPermissions(unGrantPermission.toTypedArray(),100)
                return false
            }
        }
        return true
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode==100 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            unGrantPermission.forEach {
                if(checkSelfPermission(it) == PackageManager.PERMISSION_DENIED){
                    hasUnGranted=true
                }
            }
        }

        if(hasUnGranted){
            AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("请授权权限")
                .setPositiveButton("去设置"){dialog,_->
                    dialog.dismiss()
                    hasUnGranted=false
                    jumpToAppDetail()
                }
                .setNegativeButton("取消"){dialog,_->
                    dialog.dismiss()
                    hasUnGranted =false
                }
                .show()
        }
    }
    //跳转到应用设置页面
    private fun jumpToAppDetail(){
        this@MainActivity.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
            data = Uri.fromParts("package",packageName,null)
        })
    }

}